package cn.achao.csr.sequence.service;


import cn.achao.csr.sequence.core.IDGen;
import cn.achao.csr.sequence.core.common.Result;
import cn.achao.csr.sequence.core.common.ZeroIDGen;
import cn.achao.csr.sequence.core.exception.InitException;
import cn.achao.csr.sequence.core.segment.SegmentIDGenImpl;
import cn.achao.csr.sequence.core.segment.dao.IDAllocDao;
import cn.achao.csr.sequence.core.segment.dao.impl.IDAllocDaoImpl;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

@Service("SegmentService")
public class SegmentService {
    private Logger logger = LoggerFactory.getLogger(SegmentService.class);

    private IDGen idGen;
    private DruidDataSource dataSource;


    /**
     * 通过构造函数注入@Value可以接受外部配置
     * @param flag
     * @param url
     * @param username
     * @param password
     * @throws SQLException
     * @throws InitException
     */
    public SegmentService(
            @Value("${leaf.segment.enable:true}") boolean flag,
            @Value("${spring.datasource.url}") String url,
            @Value("${spring.datasource.username}") String username,
            @Value("${spring.datasource.password}") String password
    ) throws SQLException, InitException {

        if (flag) {
            // Config dataSource
            dataSource = new DruidDataSource();
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            dataSource.init();

            // Config Dao
            IDAllocDao dao = new IDAllocDaoImpl(dataSource);

            // Config ID Gen
            idGen = new SegmentIDGenImpl();
            ((SegmentIDGenImpl) idGen).setDao(dao);
            if (idGen.init()) {
                logger.info("Segment Service Init Successfully");
            } else {
                throw new InitException("Segment Service Init Fail");
            }
        } else {
            idGen = new ZeroIDGen();
            logger.info("Zero ID Gen Service Init Successfully");
        }
    }

    public Result getId(String key) {
        return idGen.get(key);
    }

    public SegmentIDGenImpl getIdGen() {
        if (idGen instanceof SegmentIDGenImpl) {
            return (SegmentIDGenImpl) idGen;
        }
        return null;
    }
}
